/**
 * 通用统计
 */
import React from 'react'
import { Table, Form, DatePicker, Button } from 'antd'
import { fetchPost } from '../../../../utils/request'

const { RangePicker } = DatePicker
const FormItem = Form.Item
import moment from 'moment'
import { origin } from '../../../../utils/config'

class TimeRelatedForm extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      data: [],
      columns: [],
      params: {},
      statsKey: null,
      startDate: null,
      endDate: null,
      isShowDateSelect: this.props.isShowDateSelect,
      xLength: 2000
    }
  }

  componentDidMount () {
    let statsKey = null
    if (this.props.params != null && this.props.params.statsKey != null) {
      statsKey = this.props.params.statsKey
    } else {
      statsKey = this.props.statsKey
    }
    this.setState({
      statsKey: statsKey,
      startDate: this.getStartDate(),
      endDate: this.getStartDate()
    }, () => {
      let startDate = this.getStartDate()
      this.getData(startDate, startDate)
    })
  }

  componentWillReceiveProps (props) {
    let statsKey = null
    if (props.params != null && props.params.statsKey != null) {
      statsKey = props.params.statsKey
    } else {
      statsKey = props.statsKey
    }

    this.setState({
      statsKey: statsKey
    })
  }

  getData (startDate, endDate) {
    let url = '/stats/' + this.state.statsKey
    let param = {
      ...this.state.params,
      startDate: startDate,
      endDate: endDate
    }
    fetchPost(url, param).then(json => {
      if (json && json.data != null && json.code === 0) {
        let { data, keyList } = json.data
        let columns = []
        let xLengthTmp = 0
        if (keyList.length > 0 && keyList != null) {
          keyList.map(item => {
            columns.push({
              title: item,
              dataIndex: item,
              key: item
            })
            xLengthTmp += item.length
          })

          // let sum = []
          // let i = 0
          // data.map(function (dt) {
          //   let eachKeys = Object.keys(dt)
          //   eachKeys.map(function (eachKey) {
          //     if (typeof (sum[eachKey]) == 'undefined') {
          //       if (eachKey.indexOf('数') !== -1)
          //         sum[eachKey] = dt[eachKey]
          //       else if (eachKey.indexOf('日期') !== -1)
          //         sum[eachKey] = '合计'
          //     } else if (eachKey.indexOf('数') !== -1) {
          //       sum[eachKey] += dt[eachKey]
          //     }
          //   })
          //   i++
          // })
          //
          // let obj = {}
          // Object.assign(obj, sum)
          // data.push(obj)

          this.setState({
            data: data,
            columns: columns,
            xLength: xLengthTmp * 6.8 //按标题计算宽度
          })
        } else {
          this.setState({
            data: data
          })
        }

      } else {
        this.setState({
          data: []
        })
      }
    })
  }

  changeParams (params) {
    this.setState({
      params,
    }, () => {
      this.getData()
    })
  }

  handleSubmit = (e) => {
    e.preventDefault()
    this.props.form.validateFields((err, fieldsValue) => {
      const rangeValue = fieldsValue['range-picker']
      let startDate = rangeValue[0]
      let endDate = rangeValue[1]
      this.setState({
        startDate: startDate.format('YYYY-MM-DD'),
        endDate: endDate.format('YYYY-MM-DD')
      })

      this.getData(startDate.format('YYYY-MM-DD'), endDate.format('YYYY-MM-DD'))
    })
  }

  getStartDate () {
    let date = new Date()
    let separator = '-'
    let year = date.getFullYear()
    let month = date.getMonth() + 1
    let strDate = date.getDate()
    if (month >= 1 && month <= 9) {
      month = '0' + month
    }
    if (strDate >= 0 && strDate <= 9) {
      strDate = '0' + strDate
    }
    return year + separator + month + separator + strDate
  }

  handelExport = () => {
    const { statsKey, startDate, endDate } = this.state
    let url = `${origin}/stats/${statsKey}/export?startDate=${startDate}&endDate=${endDate}`
    window.open(url)
  }

  render () {
    const dateFormat = 'YYYY-MM-DD'
    const rangeConfig = {
      rules: [{ type: 'array', required: true, message: 'Please select Time!' }],
      initialValue: [moment(this.state.startDate, dateFormat), moment(this.state.startDate, dateFormat)]
    }

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
    }

    const itemLayout = {
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 16, offset: 8 },
      }
    }
    const { getFieldDecorator } = this.props.form
    return (
      <div>
        <div style={{ width: 600 }}>

          {this.state.isShowDateSelect == '0' ? null :
            <Form layout="inline" onSubmit={this.handleSubmit}>
              <FormItem
                {...formItemLayout}
                label="Date"

              >
                {getFieldDecorator('range-picker', rangeConfig)(
                  <RangePicker/>
                )}
              </FormItem>

              <FormItem {...itemLayout} >
                <Button type="primary" htmlType="submit">Search</Button>
              </FormItem>

              <FormItem {...itemLayout} >
                <Button type="primary" onClick={this.handelExport}>Export</Button>
              </FormItem>
            </Form>}

        </div>
        <div className="mt20">
          <Table
            pagination={false}
            bordered
            scroll={{ x: this.state.xLength }}
            size='small'
            dataSource={this.state.data}
            columns={this.state.columns}
            title={() => 'Result'}
          />
        </div>
      </div>
    )
  }
}

const WrappedTimeRelatedForm = Form.create()(TimeRelatedForm)

export default WrappedTimeRelatedForm

